<?php

namespace common\logics\trade;

use Yii;
use common\models\trade\TradePartner;
use common\models\trade\TradePaymode;
use common\logics\trade\scope\CompatibleScopeInterface;
use common\models\shop\ShopOrder;
use common\models\shop\ShopOrderGoods;
use common\models\shop\ShopProduct;
use common\models\shop\ShopOrderDiscount;
use common\models\shop\ShopOrderUnified;

/**
 * 统一订单组合支付积分付款比例均摊模型
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class CreditShareModel extends \common\base\Model {

    use \common\traits\Constants;

    /**
     * @var integer 统一订单ID
     */
    public $unified_id;

    /**
     * @var float 付款总金额
     */
    public $amount;

    /**
     * @var float 付款积分金额
     */
    public $credit;

    /**
     * @var ShopOrderUnified|null 业务订单模型
     */
    private $_unifiedOrder = null;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['unified_id', 'amount', 'credit'], 'required'],
            [['amount', 'credit'], 'number'],
            ['amount', 'compare', 'compareValue' => 0, 'operator' => '>'],
            ['unified_id', 'validateUnifiedOrder'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'order_id' => '订单ID',
            'user_id' => '用户ID',
            'paymode' => '支付方式',
            'scope' => '业务类型',
            'partner_id' => '商户ID',
        ];
    }

    /**
     * 校验订单信息
     */
    public function validateUnifiedOrder($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $unifiedOrder = ShopOrderUnified::findOne($this->$attribute);
        if (!$unifiedOrder) {
            $this->addError($attribute, '统一订单信息不存在');
        }
        $this->_unifiedOrder = $unifiedOrder;
    }

    /**
     * 统一金额单位（分）
     * @param float|string|integer $value 数值
     * @return integer
     */
    protected function unifiedAmountUnitFee($value) {
        return intval($value * 100);
    }

    /**
     * @return ShopOrderUnified
     */
    protected function getUnifiedOrder() {
        return $this->_unifiedOrder;
    }

    /**
     * 支付总金额（分）
     * @return integer
     */
    protected function getAmountFee() {
        return $this->unifiedAmountUnitFee($this->amount);
    }

    /**
     * 支付积分总金额（分）
     * @return integer
     */
    protected function getCreditFee() {
        return $this->unifiedAmountUnitFee($this->credit);
    }

    /**
     * 支付现金总金额（分）
     * @return integer
     */
    protected function getCashFee() {
        return round($this->getAmountFee() - $this->getCreditFee());
    }

    /**
     * 积分付款金额占总付款金额的比例
     * @return float
     */
    protected function getCreditRate() {
        return $this->credit / $this->amount;
    }

    /**
     * 均摊计算
     */
    public function shareReckon() {
        if (!$this->validate()) {
            return $this->dumpError('');
        }

        $unifiedOrder = $this->getUnifiedOrder();

        //统一金额单位（分）
        $expressPriceFee = $this->unifiedAmountUnitFee($unifiedOrder->express_price);
        $payAmountFee = $this->getAmountFee();
        $payCreditFee = $this->getCreditFee();
        $payCashFee = $this->getCashFee();

        $creditPayRate = $this->getCreditRate();

        /* @var $orderDiscounts ShopOrderDiscount[] */
        $orderDiscounts = $unifiedOrder->discounts;
        $goodsDiscounts = [];
        foreach ($orderDiscounts as $orderDiscount) {
            $discountFee = $this->unifiedAmountUnitFee($orderDiscount->discount);
            $orderGoodsId = $orderDiscount->order_goods_id;
            if (isset($goodsDiscounts[$orderGoodsId])) {
                $goodsDiscounts[$orderGoodsId] += $discountFee;
            } else {
                $goodsDiscounts[$orderGoodsId] = $discountFee;
            }
        }

        //暂存统一订单支付商品总价积分总金额
        $tempCreditFee = $payCreditFee;
        echo '临时记录剩余积分：' . $tempCreditFee . '<br>';
        $residueGoods = null;

        /* @var $orderGoods ShopOrderGoods[] */
        $orderGoods = $unifiedOrder->goods;
        foreach ($orderGoods as $goods) {
//            $shopOrder->
        }

        /* @var $shopOrders ShopOrder[] */
        $shopOrders = $unifiedOrder->orders;

        foreach ($shopOrders as $shopOrder) {
            
        }
    }

    /**
     * 计算订单商品积分比例分摊数值
     * 
     * @params ShopOrderGoods[] $orderGoods
     * @params integer $credits
     */
    protected function reckonGoodsCredit($orderGoods) {
        //暂存统一订单支付商品总价积分总金额
        $tempCreditFee = $this->getCreditFee();
        $residueGoods = null;
        foreach ($orderGoods as $goods) {
            $goodsPayAmount = $goods['goods_price'] * $goods['goods_number'];
            echo '商品原始价：' . $goodsPayAmount . '<br>';
            if (isset($goodsDiscounts[$goods['id']])) {
                $goods['goods_discount'] = $goodsDiscounts[$goods['id']];
                echo '商品折扣金额：' . $goods['goods_discount'] . '<br>';
                $goodsPayAmount -= $goods['goods_discount'];
            }
            echo '商品总价：' . $goodsPayAmount . '<br>';
            //当前订单商品最大可用积分数
            $goodsMaxUseCredits = $goods['maxDeductCredits'];
            echo '商品最大可以积分金额：' . $goodsMaxUseCredits . '<br>';
            if ($goodsPayAmount > 0 && $goodsAmountCredit > 0) {
                //计算订单积分比例按照向下取整方式，利于循环直接取舍，不用额外判断剩余积分是否大于0
                $curentGoodsCreditFee = min(round($goodsPayAmount * $creditPayRate * 10), $goodsMaxUseCredits) * 10;
                echo '当前商品需分摊的积分金额：' . $curentGoodsCreditFee . '<br>';
                if ($curentGoodsCreditFee > $tempCreditFee) {
                    echo '当前商品分摊的积分金额已超过总金额：' . $curentGoodsCreditFee . '>' . $tempCreditFee . '<br>';
                    $curentGoodsCreditFee = $tempCreditFee;
                    echo '将剩余金额应用到当前商品需分摊的积分金额：' . $curentGoodsCreditFee . '<br>';
                }
                $tempCreditFee -= $curentGoodsCreditFee;
                $goods['pay_credit'] = intval($curentGoodsCreditFee / 10);
                echo '计算得到商品的实际支付积分：' . $curentGoodsCreditFee . '<br>';
            }
            $saveGoods[$goods['id']] = $goods;
            $residueGoods = $goods['id'];
            echo '<hr>';
        }
    }

    /**
     * 订单商品积分比例分摊
     * 
     * @params ShopOrderUnified $order
     * @params integer $credits
     */
    function shareGoodsCreditFee($shopOrders, $orderGoods, $orderDiscounts, $expressPrice, $payCredit, $payAmount) {
        $saveGoods = [];
        $saveOrders = [];
        //统一金额单位（分）
        $payAmountFee = intval($payAmount * 100);
        $payCreditFee = intval($payCredit * 10);
        $expressPriceFee = intval($expressPrice * 100);

        //积分付款金额占总付款金额的比例
        $creditPayRate = $payCreditFee / $payAmountFee;
        echo '积分付款金额占总付款金额的比例：' . $creditPayRate . '<br>';
        //去除运费比例后计算商品总价积分
        $goodsAmountCredit = intval($payCredit - $expressPrice / $payAmount * $payCredit);
        echo '去除运费比例后计算商品总价积分：' . $goodsAmountCredit . '<br>';
        //统一订单运费积分金额占比金额
        $expressCredit = intval($payCredit - $goodsAmountCredit);
        echo '统一订单运费积分金额占比金额：' . $expressCredit . '<br>';
        /* @var $shopOrderGoods ShopOrderGoods[] */
        $shopOrderGoods = $orderGoods;
        /* @var $shopOrderDiscounts ShopOrderDiscount[] */
        $shopOrderDiscounts = $orderDiscounts;
        $goodsDiscounts = [];
        foreach ($shopOrderDiscounts as $orderDiscount) {
            if (isset($goodsDiscounts[$orderDiscount['order_goods_id']])) {
                $goodsDiscounts[$orderDiscount['order_goods_id']] += $orderDiscount['discount'];
            } else {
                $goodsDiscounts[$orderDiscount['order_goods_id']] = $orderDiscount['discount'];
            }
        }

        //暂存统一订单支付商品总价积分总金额
        $tempCreditFee = $payCreditFee;
        echo '临时记录剩余积分：' . $tempCreditFee . '<br>';
        $residueGoods = null;

        echo '<hr>';
        foreach ($shopOrderGoods as $goods) {
            $goodsPayAmount = $goods['goods_price'] * $goods['goods_number'];
            echo '商品原始价：' . $goodsPayAmount . '<br>';
            if (isset($goodsDiscounts[$goods['id']])) {
                $goods['goods_discount'] = $goodsDiscounts[$goods['id']];
                echo '商品折扣金额：' . $goods['goods_discount'] . '<br>';
                $goodsPayAmount -= $goods['goods_discount'];
            }
            echo '商品总价：' . $goodsPayAmount . '<br>';
            //当前订单商品最大可用积分数
            $goodsMaxUseCredits = $goods['maxDeductCredits'];
            echo '商品最大可以积分金额：' . $goodsMaxUseCredits . '<br>';
            if ($goodsPayAmount > 0 && $goodsAmountCredit > 0) {
                //计算订单积分比例按照向下取整方式，利于循环直接取舍，不用额外判断剩余积分是否大于0
                $curentGoodsCreditFee = min(round($goodsPayAmount * $creditPayRate * 10), $goodsMaxUseCredits) * 10;
                echo '当前商品需分摊的积分金额：' . $curentGoodsCreditFee . '<br>';
                if ($curentGoodsCreditFee > $tempCreditFee) {
                    echo '当前商品分摊的积分金额已超过总金额：' . $curentGoodsCreditFee . '>' . $tempCreditFee . '<br>';
                    $curentGoodsCreditFee = $tempCreditFee;
                    echo '将剩余金额应用到当前商品需分摊的积分金额：' . $curentGoodsCreditFee . '<br>';
                }
                $tempCreditFee -= $curentGoodsCreditFee;
                $goods['pay_credit'] = intval($curentGoodsCreditFee / 10);
                echo '计算得到商品的实际支付积分：' . $curentGoodsCreditFee . '<br>';
            }
            $saveGoods[$goods['id']] = $goods;
            $residueGoods = $goods['id'];
            echo '<hr>';
        }

        $expressCreditFee = round($expressPriceFee * $creditPayRate);
        if ($expressCreditFee > $tempCreditFee) {
            echo '当前运费的积分金额已超过总金额：' . $expressCreditFee . '>' . $tempCreditFee . '<br>';
            $expressCreditFee = $tempCreditFee;
            echo '将剩余金额应用到当前运费需分摊的积分金额：' . $expressCreditFee . '<br>';
        }

        $tempCreditFee -= $expressCreditFee;

        //补入最后一个订单商品（暂时暴力补录）
        if ($tempCreditFee > 0) {
            if ($expressPriceFee > 0) {
                echo '补入订单运费：' . $tempCreditFee . '<br>';
                $expressCreditFee += $tempCreditFee;
                echo '补入后订单运费实际支付积分：' . $expressCreditFee . '<br>';
            } else {
                echo '补入最后一个订单商品（暂时暴力补录）：' . $tempCreditFee . '<br>';
                $saveGoods[$residueGoods]['pay_credit'] += intval($tempCreditFee / 10);
                echo '补入后商品实际支付积分：' . $saveGoods[$residueGoods]['pay_credit'] . '<br>';
            }
        }
        echo '<hr>';

        $tempExpressCreditFee = $expressCreditFee;
        echo '临时记录运费积分：' . $tempExpressCreditFee . '<br>';
        echo '<hr>';
        foreach ($shopOrders as $shopOrder) {
            if ($payAmount > 0 && $payCredit > 0) {
                $shopOrderExpressCreditFee = round($shopOrder['express_price'] * $creditPayRate * 100);
                echo '当前订单运费需分摊的积分金额：' . $shopOrderExpressCreditFee . '<br>';
                if ($shopOrderExpressCreditFee > $tempExpressCreditFee) {
                    echo '当前订单运费分摊的积分金额已超过总金额：' . $shopOrderExpressCreditFee . '>' . $tempExpressCreditFee . '<br>';
                    $shopOrderExpressCreditFee = $tempExpressCreditFee;
                    echo '将剩余金额应用到当前订单运费需分摊的积分金额：' . $shopOrderExpressCreditFee . '<br>';
                }
                $tempExpressCreditFee -= $shopOrderExpressCreditFee;

                $shopOrderGoodsPayCredit = 0;
                foreach ($saveGoods as $_sg) {
                    if ($_sg['order_id'] == $shopOrder['id']) {
                        $shopOrderGoodsPayCredit += $_sg['pay_credit'];
                    }
                }
                echo '重新计算订单商品的积分支付总额：' . $shopOrderGoodsPayCredit . '<br>';
                $shopOrder['pay_credit'] = $shopOrderGoodsPayCredit + intval($shopOrderExpressCreditFee / 10);
                echo '计算得到订单的实际支付积分：' . $shopOrder['pay_credit'] . '<br>';
            }
            $saveOrders[] = $shopOrder;
            echo '<hr>';
        }
        return [
            'goods' => $saveGoods,
            'orders' => $saveOrders,
        ];
    }

}
